package rsa;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.KeyPair;

public class RsaTools {
	
	public static KeyPair createRSAKeyPair(String filename) {
		try {
			RsaFunktionen rsa = new RsaFunktionen();
			KeyPair keyPair = rsa.schluesselErstellen();
			
			System.out.println(keyPair.getPublic());
			writeKeyPair(filename, keyPair);
			return keyPair;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void writeKeyPair(String filename, KeyPair keyPair) {
		OutputStream fos = null;

		try {
			fos = new FileOutputStream(filename);
			ObjectOutputStream o = new ObjectOutputStream(fos);
			o.writeObject(keyPair);
		} catch (IOException e) {
			System.err.println(e);
		} finally {
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}
	
	public KeyPair readKeyPair(String filename) {
		InputStream fis = null;
		KeyPair keys = null;
		try {
			File file = new File(filename);
			if(file.exists()) {
				fis = new FileInputStream(file);
				ObjectInputStream o = new ObjectInputStream(fis);
				keys = (KeyPair) o.readObject();
			} 
			

		} catch (IOException e) {
			System.err.println(e);
		} catch (ClassNotFoundException e) {
			System.err.println(e);
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return keys;
	}
	
	public KeyPair checkRSAKeyPair(String filename) 
	{
		File file = new File(filename);
		if(file.exists()) {
			return readKeyPair(filename);
		} else {
			return createRSAKeyPair(filename);
		}
	}

}
